package com.sparrow.socket.tcp.codec;

import com.sparrow.socket.util.PacketHelper;
import com.sparrow.socket.util.CodecUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class RequestDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        int msgId = byteBuf.readInt();
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        Class<?> clazz = PacketHelper.getClass(msgId);
        if (clazz == null) {
            // 可以考虑关闭连接或者记录日志
            ctx.close();
            throw new IllegalStateException("Unknown msgId: " + msgId);
        }
        Object msgPacket = CodecUtil.decode(clazz, bytes);
        Request request = new Request();
        request.setMsgId(msgId);
        request.setMsg(msgPacket);
        out.add(request);
    }
}
